package com.atguigu.demo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class AirCondition {//资源类 = Field + Method
    int num = 0;
 /*   public synchronized void increment() throws InterruptedException {
        while (num!=0){
            this.wait();
        }
        //2 干活
        System.out.println(Thread.currentThread().getName()+"\t"+(++num));
        //3 通知
        this.notifyAll();
    }
    public synchronized void decrement() throws InterruptedException {
        while (num==0){
            this.wait();
        }
        //2 干活
        System.out.println(Thread.currentThread().getName()+"\t"+(--num));
        //3 通知
        this.notifyAll();
    }*/

    Lock lock =new ReentrantLock();
    Condition condition = lock.newCondition();
    public void increment() throws InterruptedException {
        lock.lock();
        try {
            while (num!=0){
                condition.await();
            }
            //2 干活
            System.out.println(Thread.currentThread().getName()+"\t"+(++num));
            //3 通知
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            while (num==0){
                condition.await();
            }
            //2 干活
            System.out.println(Thread.currentThread().getName()+"\t"+(--num));
            //3 通知
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}
public class ProdConsumerDemo {
    public static void main(String[] args) {
        AirCondition airCondition = new AirCondition();
        new Thread(()->{
            for (int i = 0; i<10;i++){
                try {
                    airCondition.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i<10;i++){
                try {
                    airCondition.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i<10;i++){
                try {
                    airCondition.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
        new Thread(()->{
            for (int i = 0; i<10;i++){
                try {
                    airCondition.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }
}
